package top.smallway.lightbandassistant_app.adapter;


import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static top.smallway.lightbandassistant_app.method.Method.secondsToTimeFormat;
import static top.smallway.lightbandassistant_app.network.Okhttp.DelStartListKey;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.UI.AboutSong;
import top.smallway.lightbandassistant_app.UI.MyStartActivity;
import top.smallway.lightbandassistant_app.data.Keys;
import top.smallway.lightbandassistant_app.data.Song_Data;
import top.smallway.lightbandassistant_app.method.Method;
import top.smallway.lightbandassistant_app.network.Search;

/**
 * 收藏歌曲列表适配器
 * 负责显示用户收藏的歌曲列表，实现歌曲项的展示、点击查看详情和长按删除功能
 */
public class StartAdapter extends RecyclerView.Adapter<StartAdapter.MyViewHolder> {
    /**
     * 构造函数
     * @param data 收藏歌曲数据列表
     * @param context 上下文对象
     */
    public StartAdapter(List<Keys> data, Context context) {
        this.data = data;
        this.context = context;
    }

    // 收藏歌曲数据列表
    private List<Keys> data;
    // 上下文对象
    private final Context context;
    // 是否启用加载更多功能
    private boolean mIsLoadMoreEnabled = false;
    // 加载提示弹窗
    private BasePopupView xPopup;


    @NonNull
    /**
     * 创建ViewHolder
     * @param parent 父视图组
     * @param viewType 视图类型
     * @return 返回创建的ViewHolder
     */
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.songs_items2, parent, false);
        return new MyViewHolder(view);
    }

    @SuppressLint({"ResourceAsColor", "SetTextI18n"})
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        Keys keys = data.get(position);
        holder.songname.setText(keys.getName());
        holder.songname.setFocusable(true);
        holder.key.setText("歌曲KEY：" + keys.getKey());
        Glide.with(holder.itemView.getContext()).load("https://na.cdn.beatsaver.com/" + keys.getHash() + ".jpg").placeholder(R.drawable.pgbar).error(R.drawable.loadingerror).into(holder.SongPicture);
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                new XPopup.Builder(v.getContext()).asConfirm("光团助手", "是否删除\"" + keys.getName() + "\"的收藏？", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String message = DelStartListKey(keys.getPk());
                                Activity activity = (Activity) v.getContext();
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (message != null) {
                                            Toast.makeText(v.getContext(), message, Toast.LENGTH_SHORT).show();
                                        }
                                        MyStartActivity.updata();

                                    }
                                });
                            }
                        }).start();
                    }
                }).show();
                return true;
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xPopup = new XPopup.Builder(context).asLoading("正在加载中").show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String respond = Search.getsong(data.get(position).getKey(), 0);
                            Song_Data song_data = Method.unmarshalSongData(respond);
                            assert song_data != null;
                            startActivity(AboutSong.fromDataToIntent(context, song_data));
                            xPopup.smartDismiss();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * 更新收藏歌曲数据
     * @param newData 新的歌曲数据列表
     */
    @SuppressLint("NotifyDataSetChanged")
    public void updateData(List<Keys> newData) {
        data = new ArrayList<>();
        Log.d("data", data.toString());
        data.addAll(newData);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mIsLoadMoreEnabled ? (data == null ? 1 : data.size() + 1) : (data == null ? 0 : data.size());
    }

    /**
     * 视图持有者类
     * 用于缓存歌曲项的视图组件
     */
    public class MyViewHolder extends RecyclerView.ViewHolder {
        private final ImageView SongPicture;
        private final TextView songname;
        private final TextView key;
        private final LinearLayout inter;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            SongPicture = itemView.findViewById(R.id.SongPicture);
            songname = itemView.findViewById(R.id.songname);
            key = itemView.findViewById(R.id.key);
            inter = itemView.findViewById(R.id.inter);

        }
    }
}
